import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intl/intl.dart';

import '../models/family_member.dart';
import '../providers/family_providers.dart';

/// 添加或编辑家庭成员对话框
class AddMemberDialog extends ConsumerStatefulWidget {
  /// 要编辑的成员（如果为null则表示添加新成员）
  final FamilyMember? memberToEdit;

  /// 构造函数
  const AddMemberDialog({Key? key, this.memberToEdit}) : super(key: key);

  @override
  ConsumerState<AddMemberDialog> createState() => _AddMemberDialogState();
}

class _AddMemberDialogState extends ConsumerState<AddMemberDialog> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _phoneController = TextEditingController();
  final _emailController = TextEditingController();
  
  late FamilyRole _selectedRole;
  DateTime? _selectedBirthday;
  String? _avatarUrl;

  @override
  void initState() {
    super.initState();
    
    // 如果是编辑模式，则使用现有成员的数据初始化表单
    if (widget.memberToEdit != null) {
      final member = widget.memberToEdit!;
      _nameController.text = member.name;
      _selectedRole = member.role;
      _selectedBirthday = member.birthday;
      _avatarUrl = member.avatarUrl;
      
      if (member.phoneNumber != null) {
        _phoneController.text = member.phoneNumber!;
      }
      
      if (member.email != null) {
        _emailController.text = member.email!;
      }
    } else {
      // 添加新成员，使用默认值
      _selectedRole = FamilyRole.other;
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _phoneController.dispose();
    _emailController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(widget.memberToEdit == null ? '添加家庭成员' : '编辑家庭成员'),
      content: SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 头像选择
              Center(
                child: Stack(
                  children: [
                    CircleAvatar(
                      radius: 40.r,
                      backgroundImage: _avatarUrl != null ? NetworkImage(_avatarUrl!) : null,
                      child: _avatarUrl == null ? Icon(Icons.person, size: 40.r) : null,
                    ),
                    Positioned(
                      right: 0,
                      bottom: 0,
                      child: Container(
                        padding: EdgeInsets.all(4.w),
                        decoration: const BoxDecoration(
                          color: Colors.blue,
                          shape: BoxShape.circle,
                        ),
                        child: InkWell(
                          onTap: _pickAvatar,
                          child: Icon(
                            Icons.camera_alt,
                            color: Colors.white,
                            size: 16.sp,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 16.h),
              
              // 姓名输入框
              TextFormField(
                controller: _nameController,
                decoration: const InputDecoration(
                  labelText: '姓名',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入姓名';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16.h),
              
              // 角色选择器
              DropdownButtonFormField<FamilyRole>(
                decoration: const InputDecoration(
                  labelText: '家庭角色',
                  border: OutlineInputBorder(),
                ),
                value: _selectedRole,
                items: FamilyRole.values.map((role) {
                  return DropdownMenuItem<FamilyRole>(
                    value: role,
                    child: Row(
                      children: [
                        Icon(role.icon, size: 20.sp),
                        SizedBox(width: 8.w),
                        Text(role.displayName),
                      ],
                    ),
                  );
                }).toList(),
                onChanged: (value) {
                  if (value != null) {
                    setState(() {
                      _selectedRole = value;
                    });
                  }
                },
              ),
              SizedBox(height: 16.h),
              
              // 生日选择器
              InkWell(
                onTap: () => _selectBirthday(context),
                child: InputDecorator(
                  decoration: const InputDecoration(
                    labelText: '生日',
                    border: OutlineInputBorder(),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        _selectedBirthday != null
                            ? DateFormat('yyyy年MM月dd日').format(_selectedBirthday!)
                            : '点击选择生日',
                      ),
                      const Icon(Icons.calendar_today),
                    ],
                  ),
                ),
              ),
              SizedBox(height: 16.h),
              
              // 手机号输入框
              TextFormField(
                controller: _phoneController,
                decoration: const InputDecoration(
                  labelText: '手机号（可选）',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.phone,
              ),
              SizedBox(height: 16.h),
              
              // 邮箱输入框
              TextFormField(
                controller: _emailController,
                decoration: const InputDecoration(
                  labelText: '邮箱（可选）',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.emailAddress,
              ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: _saveMember,
          child: Text(widget.memberToEdit == null ? '添加' : '保存'),
        ),
      ],
    );
  }

  /// 选择生日
  Future<void> _selectBirthday(BuildContext context) async {
    final picked = await showDatePicker(
      context: context,
      initialDate: _selectedBirthday ?? DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime.now(),
    );
    
    if (picked != null) {
      setState(() {
        _selectedBirthday = picked;
      });
    }
  }

  /// 选择头像
  void _pickAvatar() {
    // 在实际应用中，这里应该实现图片选择和上传功能
    // 为了简化示例，这里使用随机头像
    setState(() {
      // 使用随机头像服务
      final randomId = DateTime.now().millisecondsSinceEpoch % 1000;
      _avatarUrl = 'https://i.pravatar.cc/150?img=$randomId';
    });
  }

  /// 保存成员
  void _saveMember() {
    if (_formKey.currentState!.validate()) {
      if (widget.memberToEdit != null) {
        // 更新现有成员
        final updatedMember = widget.memberToEdit!.copyWith(
          name: _nameController.text,
          role: _selectedRole,
          birthday: _selectedBirthday,
          avatarUrl: _avatarUrl,
          phoneNumber: _phoneController.text.isEmpty ? null : _phoneController.text,
          email: _emailController.text.isEmpty ? null : _emailController.text,
        );
        
        ref.read(familyProvider.notifier).updateMember(updatedMember);
      } else {
        // 添加新成员
        ref.read(familyProvider.notifier).addMember(
              name: _nameController.text,
              role: _selectedRole,
              birthday: _selectedBirthday,
              avatarUrl: _avatarUrl,
              phoneNumber: _phoneController.text.isEmpty ? null : _phoneController.text,
              email: _emailController.text.isEmpty ? null : _emailController.text,
            );
      }
      
      Navigator.pop(context);
    }
  }
}
